using UnityEngine;
using System.Collections;

public class GridScript : MonoBehaviour {
	public int Width;
	public int Length;
	
	public int MaxHeight;
	public int MaxHeightChange;
	
	public float Stability;
	
	public int[,] Initialize()
	{
		var heightMap = new int[Width, Length];
		var tile = (GameObject) Resources.Load("Tile");
		var height = Random.Range(0, MaxHeight);
		for (var i = 0; i < Width; i++)
		{
			for (var k = 0; k < Length; k++)
			{
				if (MaxHeight > 0 && Random.value > Stability)
				{
					var left = height;
					var top = height;
					if (k > 0)
					{
						top = heightMap[i, k - 1];
					}
					if (i > 0)
					{
						left = heightMap[i - 1, k];
					}
					
					// Finding the overlapping range
					var min = Mathf.Max(new int[]{left - MaxHeightChange, top - MaxHeightChange});
					var max = Mathf.Min(new int[]{left + MaxHeightChange, top + MaxHeightChange});
					Debug.Log("Left Height: " + left);
					Debug.Log("Top Height: " + top);
					
					// Accounting for bottom of map
					if (min < 0)
					{
						min = 0;
					}
					// Accounting max height
					if (max > MaxHeight)
					{
						max = MaxHeight;
					}
					
					// Picking a random height that isn't the current height
					if (min == height && min < MaxHeight)
					{
						min += 1;
					}
					if (max == height && max != 0)
					{
						max -= 1;
					}
					Debug.Log("Min Rand: " + min);
					Debug.Log("Max Rand: " + max);
					var rand = Random.Range(min, max);
					while (rand == height)
					{
						rand = Random.Range(min, max);
					}
					height = rand;
				}
				Debug.Log("Current Height: " + height + " (" + i + ", " + k + ")");
				heightMap[i, k] = height;
			}
		}
		for (var i = 0; i < Width; i++)
		{
			for (var k = 0; k < Length; k++)
			{
				for (var c = 0; c <= heightMap[i, k]; c++)
				{
					Instantiate(tile, new Vector3(i, c, k), new Quaternion(0f, 0f, 0f, 0f));
				}
			}
		}
		return heightMap;
	}
}
